using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.Infrastructrue.Utils;
using Medical.WriteApi.Appcontext.Command;

namespace Medical.WriteApi.Appcontext.CommandHandler
{
	public class ChangePasswordCommandHandler : IRequestHandler<ChangePasswordCommand, bool>
	{
		private readonly IBaseRepository<User> _userRepo;

		public ChangePasswordCommandHandler(IBaseRepository<User> userRepo)
		{
			_userRepo = userRepo;
		}

		public async Task<bool> Handle(ChangePasswordCommand request, CancellationToken cancellationToken)
		{
			var user = await _userRepo.GetModel(x => 
				x.UserId == request.UserId && !x.IsDeleted);
			
			if (user == null)
			{
				throw new Exception("用户不存在");
			}

			// 验证旧密码
			if (!PasswordHasher.VerifyPassword(request.OldPassword, user.PasswordHash))
			{
				throw new UnauthorizedAccessException("旧密码错误");
			}

			// 更新密码
			user.PasswordHash = PasswordHasher.HashPassword(request.NewPassword);
			user.UpdatedAt = DateTime.Now;
			await _userRepo.UpdateAsync(user);

			return true;
		}
	}
}

